class CutWords:
    def __init__(self):
        dict_path = './diseases.txt'
        self.word_dict, self.max_wordlen = self.load_words(dict_path)

    def load_words(self, dict_path):
        words = list()
        max_len = 0
        for line in open(dict_path):
            wd = line.strip()
            if not wd:
                continue
            if len(wd) > max_len:
                max_len = len(wd)
            words.append(wd)
        return words, max_len

    def max_forward_cut(self, sent):
        cutlist = []
        index = 0
        while index < len(sent):
            matched = False
            for i in range(self.max_wordlen, 0, -1):
                cand_word = sent[index: index + i]
                if cand_word in self.word_dict:
                    cutlist.append(cand_word)
                    matched = True
                    break

            if not matched:
                i = 1
                cutlist.append(sent[index])
            index += i
        return cutlist

    def max_backward_cut(self, sent):
        cutlist = []
        index = len(sent)
        while index > 0:
            matched = False
            for i in range(self.max_wordlen, 0, -1):
                tmp = (i + 1)
                cand_word = sent[index - tmp: index]
                if cand_word in self.word_dict:
                    cutlist.append(cand_word)
                    matched = True
                    break
            if not matched:
                tmp = 1
                cutlist.append(sent[index - 1])

            index -= tmp

        return cutlist[::-1]

    def max_biward_cut(self, sent):
        forward_cutlist = self.max_forward_cut(sent)
        backward_cutlist = self.max_backward_cut(sent)
        count_forward = len(forward_cutlist)
        count_backward = len(backward_cutlist)

        def compute_single(word_list):
            num = 0
            for word in word_list:
                if len(word) == 1:
                    num += 1
            return num

        if count_forward == count_backward:
            if compute_single(forward_cutlist) > compute_single(backward_cutlist):
                return backward_cutlist
            else:
                return forward_cutlist

        elif count_backward > count_forward:
            return forward_cutlist

        else:
            return backward_cutlist

